﻿import axios from "axios"
import type { LoginDto, LoginResponseDto, ApiResult } from "@/types/auth"

const api = axios.create({
  baseURL: import.meta.env.VITE_APP_API_URL || 'http://localhost:5197/api',
  timeout: 10000,
  headers: {
    "Content-Type": "application/json",
    "Cache-Control": "max-age=30",
  },
})

api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token")
    if (token) {
      (config.headers as any).Authorization = 'Bearer ' + token
    }
    return config
  },
  (error) => Promise.reject(error)
)

api.interceptors.response.use(
  (response) => {
    const payload = response.data
    if (payload && typeof payload === "object" && ("Code" in payload || "Msg" in payload || "Data" in payload)) {
      response.data = {
        msg: payload.msg ?? payload.Msg ?? "",
        code: payload.code ?? payload.Code,
        data: payload.data ?? payload.Data,
      }
    }
    return response
  },
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem("token")
      localStorage.removeItem("userInfo")
      window.location.href = "/"
    }
    return Promise.reject(error)
  }
)

export const login = async (loginData: LoginDto): Promise<ApiResult<LoginResponseDto>> => {
  const res = await api.post("/ConsoleApi/login", loginData)
  return res.data as ApiResult<LoginResponseDto>
}

export default api
